var querystring = require('querystring'),
	formidable = require('formidable'),
	util = require('util'),
	fs = require('fs');

function start(request, response) {

	 var body = '<form action="/upload" enctype="multipart/form-data" '+
			    'method="post">'+
			    '<input type="file" name="upload" multiple="multiple"><br>'+
			    '<input type="submit" value="Upload">'+
			    '</form>';
			    
	response.writeHead(200, {"Content-Type": "text/html"});
    response.write(body);
    response.end();
}

function upload(request, response) {

	console.log("Request handler 'upload' was called.");

  var form = new formidable.IncomingForm();
  form.uploadDir = "/tmp";
  console.log("about to parse");
  form.parse(request, function(error, fields, files) {
    console.log("parsing done");
    fs.rename(files.upload.path, "/tmp/test2.png");
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("received image:<br/>");
    setTimeout(function() {
    	response.write("<img src='/show' />");
    },2000);
    response.end();
  });
}

function uploadImg(request, response) {

	console.log("Request handler 'uploadImg' was called.!!!!!");
	var form = new formidable.IncomingForm();

	form.parse(request, function(err, fields, files) {

		if(err) {
			response.writeHead(500, {'Content-Type' : "text/plain"});
			response.write(err + '\n');
			response.end();

		} else {

			console.log("parsing done");
			 try{
		        fs.renameSync(files.upload.path,'tmp/test.png');
		    }catch(e){
		        console.log(e);
		        console.log('重命名图片失败');
		        console.log(files.upload.path);
		    }
			fs.renameSync(files.upload.path, "./tmp/test2.png");
			response.writeHead(200, {"Content-Type": "text/html"});
			response.write('received img:\n\n');
			response.write("<img src='/show' />");
			response.end();
		}

		
		// response.end(util.inspect({fields: fields, files: files}));
	});
}

function show(request, response) {

	console.log("Require handler 'show' was called!");

	// 读取文件
	fs.readFile('/tmp/test2.png', 'binary', function(err, file) {

		if(err) { // 读取错误

			response.writeHead(500, {'Content-Type' : "text/plain"});
			response.write(err + '\n');
			response.end();

		} else {

			response.writeHead(200, {'Content-Type' : "text/image"});
			response.write(file, 'binary');
			response.end();
		}
	});
}
exports.start = start;
exports.upload = upload;
exports.uploadImg = uploadImg;
exports.show = show;
